<template>
   <div class="Todolist">
      <div style="margin-bottom: 0.2rem;">
         <vue-hash-calendar
           visible  
           :markDate="markDate"
           markType='dot'
           @change="topDateChange"
           :max-date="maxDate"
           :isShowNotCurrentMonthDay='false'
           :isShowWeekView='true'
         >
          </vue-hash-calendar>
      </div>
      <section class="list-page">
         <div class="main">
           <van-collapse v-model="activeNames">
             <!-- 未完成 -->
            <van-collapse-item :title="`正在进行(${allTodo.notComplete ? allTodo.notComplete.length : '0'})`" name="1">
              <van-swipe-cell v-for="(item,index) in allTodo.notComplete" :key="index" :name="item.id"  :before-close="beforeClose">
                <van-checkbox-group v-model="result">
                  <van-row class="item-task" align='center' @click.stop="RowClick(item)">
                      <van-col span="2" @click.stop="markcompleted(item)">
                        <van-checkbox :name="index" class="checkbox-item"></van-checkbox>
                      </van-col>
                      <van-col span="22">
                        <div class="task-title">
                            <span class="task-title-left">{{item.title}}</span>
                            <span class="task-flag">
                              <i class="iconfont icon-biaoji" :class="{'yellow':item.levelName==='重要','red':item.levelName==='紧急' }"></i>
                              <span>{{ item.levelName }}</span>
                            </span>
                        </div>
                         <div class="taskdetail">
                           <span>{{ item.content }}</span>
                         </div>
                         <div>
                            <span class="creation-date">{{item.startTime | processingtime }}</span>
                         </div>
                      </van-col>
                  </van-row>
                </van-checkbox-group>
                  <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" />
                  </template>
              </van-swipe-cell>
            </van-collapse-item>
            <!-- 已完成 -->
            <van-collapse-item :title="`已完成(${allTodo.alreadyComplete ? allTodo.alreadyComplete.length : '0'})`" name="2">
                <van-swipe-cell v-for="(item,index) in allTodo.alreadyComplete" :key="index" :name="item.id"  :before-close="beforeClose">
                  <van-row class="item-task" align='center'>
                      <van-col span="2">
                        <i class="iconfont icon-wancheng finished"></i>
                      </van-col>
                      <van-col span="22">
                        <div class="task-title">
                            <span class="task-title-left completed-todo-title">{{item.title}}</span>
                            <span class="task-flag">
                              <i class="iconfont icon-biaoji" :class="{'yellow':item.levelName==='重要','red':item.levelName==='紧急' }"></i>
                              <span>{{ item.levelName }}</span>
                            </span>
                        </div>
                         <div class="taskdetail">
                           <span>{{ item.content }}</span>
                         </div>
                         <div>
                            <span class="creation-date">{{item.startTime | processingtime}}</span>
                         </div>
                      </van-col>
                  </van-row>
                  <template #right>
                    <van-button square text="删除" type="danger" class="delete-button" />
                  </template>
              </van-swipe-cell>

            </van-collapse-item>
        </van-collapse>
          <!-- 创建代办的表单  -->
           <van-popup v-model="addformshow"  position="bottom" :style="{ height: '45%' }"  >
             <div class="add-single">
              <van-form @submit="submitcreationTodo">
                <van-field
                  clearable
                  placeholder="准备做什么？"
                  name="title"
                  v-model="title"
                  class="add-input"
                  :rules="[{ required:true}]"
                >
                  <template #button>
                    <van-button size="small"  type="info"  :loading='add_Loading'>{{ createButtonText }}</van-button>
                  </template>
                </van-field>
                <van-field
                  v-model="content"
                  name="content"
                  type="textarea"
                  rows="2"
                  clearable
                  placeholder="添加描述"
                  show-word-limit
                  autosize
                  :rules="[{ required: false}]"
                  />
                   <van-row class="selection-time" type='flex' align='center' gutter='60px'>
                    <van-col span="5" class='event-classification'>
                        <i class="iconfont icon-biaoji" :style="'margin-right: 0.2rem'"></i>
                        <span>标记</span>
                    </van-col>
                    <van-col span="16" class='event-classification'>
                       <van-button type="primary" size="small" plain @click.prevent="levelCode=1"  class="btn-one" :class="levelCode===1 && 'actvie'">普通</van-button>
                       <van-button type="primary" size="small" plain @click.prevent="levelCode=2"  class="btn-tow" :class="levelCode===2 && 'actvie'">重要</van-button>
                       <van-button type="primary" size="small" plain @click.prevent="levelCode=3"  class="btn-three" :class="levelCode===3 && 'actvie'">紧急</van-button>
                    </van-col>
                   </van-row>
                    <!-- 时间选择器 -->
                      <van-field
                        readonly
                        clickable
                        clearable
                        label="开始时间"
                        :value="startTime"
                        name="startTime"
                        label-width='2rem'
                        placeholder="请选择任务开始的时间"
                        :rules="[{ required:true}]"
                        @click="showPicker = true"
                      />
                      <van-popup v-model="showPicker"  position="bottom" :style="{ height: '45%' }">
                        <van-datetime-picker
                          v-model="currentTime"
                          type="time"
                          @cancel="showPicker = false"
                           title="选择时间"
                          :min-hour="0"
                          :max-hour="24"
                          @confirm="onselectionTime"
                        />
                    </van-popup>
               </van-form>
             </div>
           </van-popup>
         </div>
         <div class="addTodo" @click="handeladdTodo" v-if="isAdd"><van-icon name="plus" class="add-icon"  /></div>
         <div class="placeholder" explain='占位元素'></div>
      </section>
   </div>
</template>

<script>

import moment from 'moment'
import { CreateTodo , queryTodolist ,deleteSingleData , updateSingleData ,getTagnumberofdays} from '@/api/todoApi'
import { Toast , Dialog } from 'vant';

import { reactive, toRefs, onMounted , onBeforeUnmount} from "@vue/composition-api";

export default {
  // eslint-disable-next-line no-unused-vars
  setup(props,{root}){

    const state = reactive({
      dateString:'',
      timr:null,
      addformshow:false,
      activeNames:['1'],
      // 多选数组
      result: [],
      // 按钮文字
      createButtonText:'添加',
      // 添加描述
      content:'',
      //准备做什么
      title:'',
      // 紧急程度
      levelCode:1,
      // 时间是否展开
      Dateshow:false,
      // 最小可选时间
      minDate: undefined,
      // 默认日期
      defaultDate:undefined,
      // 最大可选日期
      maxDate: undefined,
      // 日历选择器
      showCalendar:false,
      // 是否loading
      add_Loading:false,
      // 所有事项数据
      allTodo:{
        alreadyComplete:[],
        notComplete:[]
      },
      // 默认当前时间
      currentTime:'00:00',
      startTime: '',
      showPicker: false,
      // 修改id
      editId:null,
      // 日历所选时间
      calendarSelectedTime:'',
      // 当月标记天数
      markDate:[],
      isAdd:true
    })
    onMounted(() => {
        getDate()
        // 限制可选时间
        Limitoptionaltime()
    });
    // 查询标记天数
    const  queryFlageDays = async (params)=>{
      let res = await  getTagnumberofdays(params)
      state.markDate = res.payload || []
    }

    // 获得对应当天待办数据
    const getTodolistData = async(calendarSelectedTime)=>{
      var date = calendarSelectedTime 
      try {
        let res = await queryTodolist({date})
        if(res.success){
          state.allTodo = res.payload
        }
      } catch (error) {
        console.log(error);
      }
    }
    const getDate =()=>{
      var date = new Date();//实例一个时间对象；
      var hour = date.getHours();//获取系统时间
      var minute = date.getMinutes(); //分
      if(minute<10){
        minute = "0" + minute
      }
      // 默认时间为当前时间
      var currentTime = `${hour}:${minute}`
      state.currentTime = currentTime
      state.startTime = currentTime
    }

    const handeladdTodo =()=>{
      resetform()
      state.createButtonText = '添加'
      state.addformshow = true
    }

    // 点击修改
    const RowClick = (item)=>{
      const { content,levelCode,title ,id , startTime } = item;
      state.editId = id
      state.content = content;
      state.levelCode = levelCode;
      state.title = title;
      state.createButtonText = '修改';
      if(startTime){
        const timeString = startTime.split(/\s/)[1].substring(0,5)
        state.currentTime = timeString
        state.startTime= timeString
      }
      state.addformshow = true
    }
    const resetform = ()=>{
       state.add_Loading = false
       state.title = ''
       state.content = ''
       state.levelCode = 1
       getDate()
    }
    // 刷新页面
    const refreshPage = ()=>{
       resetform()
       // 重新获得数据
       getTodolistData(state.calendarSelectedTime)
    }
    // 创建todo
    const CreatetodoaApi  =  async (postData)=>{
      if(state.add_Loading){
         return
      }
      // 紧急程度
      if(state.levelCode){
          postData.levelCode = state.levelCode
      }
      // 任务开始时间
      postData.startTime = `${state.calendarSelectedTime} ${state.startTime}:00`
     try {
     // 创建
     state.add_Loading = true
     let res = await CreateTodo(postData)
     if(res.success){
       state.addformshow = false
       refreshPage()
       Toast.success('创建成功');
     }else{
       Toast.fail('创建失败了');
       state.add_Loading = false
     }
     } catch (error) {
       console.log(error);
       state.add_Loading = false
     }
    }

    // 修改数据的
    const EditTodo  =  async (postData)=>{
      if(state.add_Loading){
         return
      }
      postData.id = state.editId
      postData.startTime = `${state.calendarSelectedTime} ${state.startTime}:00`
      postData.completeCode = 1
       // 紧急程度
      if(state.levelCode){
          postData.levelCode = state.levelCode
      }
      try {
        state.add_Loading = true
        let res  = await updateSingleData(postData)
        if(res.success){
           state.addformshow = false
           refreshPage()
           Toast.success('修改成功');
           state.editId=''
        }else{
           Toast.fail('修改失败了'+res.msg);
           state.editId=''
           state.add_Loading = false
        }
     } catch (error) {
       state.editId=''
       console.log(error);
     }
    }

    // 创建一个代办事项
    const submitcreationTodo = (postData)=>{
      if(state.createButtonText === '添加'){
        CreatetodoaApi({...postData})
      }else{
        EditTodo({...postData})
      }
    }

    // 删除一个待办
   const beforeClose = ({ name, position, instance }) => {
      switch (position) {
        case 'left':
        case 'cell':
        case 'outside':
          instance.close();
          break;
        case 'right':
          Dialog.confirm({
            message: '确定删除吗？',
          }).then(async() => {
            try {
              let res = await deleteSingleData({id:name})
              if(res.success){
                Toast.success('删除成功');
                instance.close();
                // 重新获得数据
                getTodolistData(state.calendarSelectedTime)
              }
            } catch (error) {
              console.log(error);
              Toast.success('删除失败');
            }
          }).catch(err=>{console.log(err)});
          break;
      }
    }

    // 完成一个待办
    const markcompleted  = async (params) =>{
      const postData = {...params}
      postData.completeCode = 2;
      try {
        let res =  await updateSingleData(postData)
        if(res.success){
          state.result=[]
          getTodolistData(state.calendarSelectedTime)
        }else{
          state.result=[]
        }
      } catch (error) {
        console.log(error);
      }
    }

    const onselectionTime =(value)=>{
       state.startTime = value;
       state.showPicker = false;
    }

    const Limitoptionaltime= () =>{
      let dateLimit = new Date();
      //最小允许选择当前日期
      state.minDate = new Date(moment(dateLimit).format('YYYY/MM/DD'));
      //最大允许选择当前日期+1个月
      state.maxDate = new Date(moment(dateLimit).add('1','M').format('YYYY/MM/DD'));
    }


    // 顶部日历时间
    const topDateChange = (date) =>{
      state.defaultDate = date
      var filtrateDate = moment(date).format('YYYY-MM-DD');
      state.calendarSelectedTime = filtrateDate;
      getTodolistData(filtrateDate)
      // 获取当月的天数
      var thisMonthDayNumber = String(moment(date).daysInMonth())
      var yyyymm = moment(date).format('YYYY-MM')
      var start = yyyymm +'-01'
      var end = `${yyyymm}-${thisMonthDayNumber}`
      // 查询当月标记天数
      setTimeout(()=>{
        queryFlageDays({end,start})
      },1000)
      if(filtrateDate.replace(/-/g,'') < moment(new Date()).format('YYYY-MM-DD').replace(/-/g,'')){
        state.isAdd = false
      }else{
        state.isAdd = true
      }
    }

    onBeforeUnmount(()=>{
      clearInterval(state.timr)
    })

    return {
        ...toRefs(state),
        queryFlageDays,
        getTodolistData,
        getDate,
        handeladdTodo,
        RowClick,
        resetform,
        refreshPage,
        CreatetodoaApi,
        EditTodo,
        submitcreationTodo,
        beforeClose,
        markcompleted,
        onselectionTime,
        Limitoptionaltime,
        topDateChange
    }
  },
  filters:{
    processingtime(val){
      if(val){
       return val.split(/\s/)[1].substring(0,5)
      }else{
        return '-'
      }
    }
  }
}

</script>



<style lang="less" scoped>
@primary:#1989fa;
@primaryText:#333;

  .Todolist{
    width: 100%;
    position: relative;
    /deep/ .calendar_title{
      background-color: #fff;
    }
  .nav-bar{
    height: 1.22667rem;
    width: 100%;
    border-bottom: 1px solid #e5e5e5;
    position: fixed;
    background: #45a2ff;
    padding: 0 0.26667rem;
    top: 0;
    .nav-date{
      line-height: 1.22667rem;
      color: #fff;
      font-size: 26rem / 75;
    }
  }
  .placeholder{
    width: 100%;
    height: 2rem;
  }
  .placeholder-bottom{
    width: 100%;
    height: 1.22667rem;
  }
  .list-page{
    position: relative;
    overflow-y: auto;
    .addTodo{
      width: 90rem / 75;
      height: 90rem / 75;
      border-radius: 50%;
      background: #2693ff;
      position: fixed;
      bottom: 67px;
      right: 17px;
      box-shadow: 2px 3px 10px #62b1ff;
      text-align: center;
      &:active{
        background-color: @primary;
        transform:scale(1.1)
      }
      .add-icon{
        color: #fff;
        line-height: 90rem / 75;
     }
    }

  }
  .main{
    width: 100%;
    .add-single{
      padding:0 20rem/75;
      padding-top: 20rem/75;
      .add-input{
        padding-top: 0;
        padding-bottom: 0;
      }
      .selection-time{
        padding: 0.4rem 0.42667rem;
        .date-button{
          padding:0 25rem/75;
          margin-right: 0.4rem;
        }
        .event-classification{
          font-size: 28rem /75;
          color: #333;
          .icon-biaoji{
            color:#1989fa;
          }
          .btn-one{
            border-color:  rgb(228, 228, 228);
            color:rgb(160, 160, 160);
            border-radius: 5px 0 0 5px;
            padding: 0 0.5rem;
            margin-right: 0.1rem;
            &.actvie{
              background-color: rgb(228, 228, 228);
              color: #333;
            }
          }
          .btn-tow{
            border-color:  rgb(255, 187, 0);
            color: rgba(255, 187, 0, 0.863);
            padding: 0 0.5rem;
            margin-right: 0.1rem;
            &.actvie{
              background-color:  rgb(255, 187, 0);
              color: #fff;
            }
          }
          .btn-three{
            border-color:  rgb(255, 79, 79);
            color:  rgb(255, 83, 83);
            border-radius: 0 5px 5px 0 ;
            padding: 0 0.5rem;
            &.actvie{
              background-color:rgb(255, 79, 79);
              color: #fff;
            }
          }
        }
      }
      .line{
        margin: 0;
        padding: 0 0.26667rem
      }
    }
    .item-task{
      border-bottom: 1px solid #f1f1f1;
      padding: 20rem/75 0;
      font-size: 26rem/75;
      transition: all 0.3s linear;
      &:active{
        background-color: #e4e4e4;
      }
      .isdone{
        width: 50rem/75;
      }
      .checkbox-item{
        height:1.2rem;
        padding-right: 0.4rem;
      }
      .task-title{
        display: flex;
        justify-content: space-between;
        line-height: 45rem/75;
        color: @primaryText;
        .task-title-left{
          padding-right: 20rem/75;
        }
        .completed-todo-title{
          text-decoration: line-through;
        }
      }
      .taskdetail{
        display: flex;
        line-height: 45rem/75;
      }
       .creation-date{
          // white-space: nowrap
          width: 100%;
          font-size: 24rem/75;
        }
      .task-flag{
        white-space: nowrap;
        .icon-biaoji{
          color:#1989fa;
          margin-right: 10rem/75;
              &.red{
                color: rgb(255, 79, 79);
              }
              &.yellow{
                color: rgb(255, 187, 0);
            }
        }
      }
      .finished{
        font-size: 40rem/75;
      }
    }
  }

}
</style>


<style lang='less'>
  .goods-card {
    margin: 0;
    background-color: #fff;
    padding: 26rem/75 0;
    border-bottom: 1px solid #e5e5e5;
  }
  .delete-button {
    height: 100%
  }
  .done-button{
    height: 100%
  }
</style>

